package mirrormonkey.commons.graph;

import mirrormonkey.core.EntityLifecycleListener;
import mirrormonkey.framework.ConnectionInfo;
import mirrormonkey.framework.entity.StaticEntityData;
import mirrormonkey.framework.entity.SyncEntity;

import com.jme3.app.Application;
import com.jme3.app.SimpleApplication;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;

public class MakeVisibleListener implements EntityLifecycleListener {

	protected final Node attachTo;

	protected final Application application;

	public MakeVisibleListener(SimpleApplication app) {
		this(app.getRootNode(), app);
	}

	public MakeVisibleListener(Node attachTo, Application application) {
		this.attachTo = attachTo;
		this.application = application;
	}

	public void createMaterial(Geometry g) {
		Material m = new Material(application.getAssetManager(),
				"Common/MatDefs/Misc/Unshaded.j3md");
		m.setColor("Color", ColorRGBA.Blue);
		g.setMaterial(m);
	}

	@Override
	public void entityInitialized(SyncEntity entity, ConnectionInfo info) {
		if (Geometry.class.isInstance(entity)) {
			Geometry g = (Geometry) entity;
			if (g.getMaterial() == null) {
				createMaterial(g);
			}
			attachTo.attachChild(g);
		}
	}

	@Override
	public void entityReplaced(SyncEntity replacedEntity,
			StaticEntityData replacedStaticData, SyncEntity replacingEntity,
			ConnectionInfo info) {
		System.out
				.println("\n\nClient: entity " + replacedEntity + " replaced");
		entityRemoved(replacedEntity, info);
	}

	@Override
	public void entityReplacing(SyncEntity replacedEntity,
			StaticEntityData replacedStaticData, SyncEntity replacingEntity,
			ConnectionInfo info) {
		System.out.println("Client: entity " + replacingEntity
				+ " replacing\n\n");
		entityInitialized(replacingEntity, info);
	}

	@Override
	public void entityRemoved(SyncEntity entity, ConnectionInfo info) {
		if (Geometry.class.isInstance(entity)) {
			Geometry g = (Geometry) entity;
			attachTo.detachChild(g);
		}
	}

	@Override
	public int getSortingOrder() {
		return FRAMEWORK_MAX_SORTING_ORDER;
	}

}